package com.rickpan.controller;

import com.rickpan.dto.response.TeamKeyDTO;
import com.rickpan.dto.common.ApiResponse;
import com.rickpan.service.TeamKeyService;
import com.rickpan.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 团队密钥管理控制器
 * 提供团队加密密钥的获取和管理功能
 * 
 * @author RickPan Team
 * @since 2025-07-19
 */
@RestController
@RequestMapping("/api/teams/{teamId}/keys")
public class TeamKeyController {

    private static final Logger logger = LoggerFactory.getLogger(TeamKeyController.class);

    @Autowired
    private TeamKeyService teamKeyService;



    /**
     * 获取团队当前活跃密钥
     * 
     * @param teamId 团队ID
     * @param request HTTP请求
     * @return 当前活跃密钥
     */
    @GetMapping("/current")
    public ApiResponse<TeamKeyDTO> getCurrentKey(
            @PathVariable Long teamId,
            HttpServletRequest request) {
        try {
            logger.info("🔑 开始获取团队密钥: teamId={}", teamId);

            // 验证用户身份
            Long userId = SecurityUtils.getCurrentUserId();
            logger.info("🔍 当前用户ID: {}", userId);

            if (userId == null) {
                logger.warn("⚠️ 用户未认证，无法获取团队密钥: teamId={}", teamId);
                return ApiResponse.error("用户未认证");
            }

            logger.info("🔑 调用TeamKeyService获取密钥: teamId={}, userId={}", teamId, userId);
            TeamKeyDTO keyDTO = teamKeyService.getCurrentTeamKey(teamId, userId);
            logger.info("🔑 TeamKeyService返回结果: {}", keyDTO != null ? "成功" : "null");
            
            if (keyDTO == null) {
                logger.warn("⚠️ 团队密钥不存在: teamId={}", teamId);
                return ApiResponse.error("团队密钥不存在");
            }

            logger.info("✅ 成功获取团队密钥: teamId={}, keyVersion={}", teamId, keyDTO.getKeyVersion());
            return ApiResponse.success("获取团队密钥成功", keyDTO);

        } catch (Exception e) {
            logger.error("❌ 获取团队密钥失败: teamId={}, error={}", teamId, e.getMessage(), e);
            return ApiResponse.error("获取团队密钥失败: " + e.getMessage());
        }
    }

    /**
     * 获取团队指定版本的密钥
     * 
     * @param teamId 团队ID
     * @param keyVersion 密钥版本
     * @param request HTTP请求
     * @return 指定版本的密钥
     */
    @GetMapping("/version/{keyVersion}")
    public ApiResponse<TeamKeyDTO> getKeyByVersion(
            @PathVariable Long teamId,
            @PathVariable Integer keyVersion,
            HttpServletRequest request) {
        try {
            // 验证用户身份
            Long userId = SecurityUtils.getCurrentUserId();

            logger.info("🔑 获取团队指定版本密钥: teamId={}, keyVersion={}, userId={}", teamId, keyVersion, userId);

            TeamKeyDTO keyDTO = teamKeyService.getTeamKeyByVersion(teamId, keyVersion, userId);
            
            if (keyDTO == null) {
                logger.warn("⚠️ 指定版本密钥不存在: teamId={}, keyVersion={}", teamId, keyVersion);
                return ApiResponse.error("指定版本密钥不存在");
            }

            logger.info("✅ 成功获取指定版本密钥: teamId={}, keyVersion={}", teamId, keyVersion);
            return ApiResponse.success("获取密钥成功", keyDTO);

        } catch (Exception e) {
            logger.error("❌ 获取指定版本密钥失败: teamId={}, keyVersion={}, error={}", teamId, keyVersion, e.getMessage(), e);
            return ApiResponse.error("获取密钥失败: " + e.getMessage());
        }
    }

    /**
     * 轮换团队密钥（生成新版本）
     * 
     * @param teamId 团队ID
     * @param request HTTP请求
     * @return 新生成的密钥
     */
    @PostMapping("/rotate")
    public ApiResponse<TeamKeyDTO> rotateTeamKey(
            @PathVariable Long teamId,
            HttpServletRequest request) {
        try {
            // 验证用户身份
            Long userId = SecurityUtils.getCurrentUserId();

            logger.info("🔄 开始轮换团队密钥: teamId={}, userId={}", teamId, userId);

            TeamKeyDTO newKeyDTO = teamKeyService.rotateTeamKey(teamId, userId);

            logger.info("✅ 团队密钥轮换成功: teamId={}, newKeyVersion={}", teamId, newKeyDTO.getKeyVersion());
            return ApiResponse.success("密钥轮换成功", newKeyDTO);

        } catch (Exception e) {
            logger.error("❌ 团队密钥轮换失败: teamId={}, error={}", teamId, e.getMessage(), e);
            return ApiResponse.error("密钥轮换失败: " + e.getMessage());
        }
    }

    /**
     * 获取团队密钥健康状态
     * 
     * @param teamId 团队ID
     * @param request HTTP请求
     * @return 密钥健康状态
     */
    @GetMapping("/health")
    public ApiResponse<Map<String, Object>> getKeyHealth(
            @PathVariable Long teamId,
            HttpServletRequest request) {
        try {
            // 验证用户身份
            Long userId = SecurityUtils.getCurrentUserId();

            logger.info("🏥 检查团队密钥健康状态: teamId={}, userId={}", teamId, userId);

            Map<String, Object> healthStatus = teamKeyService.getKeyHealthStatus(teamId, userId);

            logger.info("✅ 成功获取密钥健康状态: teamId={}", teamId);
            return ApiResponse.success("获取密钥健康状态成功", healthStatus);

        } catch (Exception e) {
            logger.error("❌ 获取密钥健康状态失败: teamId={}, error={}", teamId, e.getMessage(), e);
            return ApiResponse.error("获取密钥健康状态失败: " + e.getMessage());
        }
    }

    /**
     * 初始化团队密钥（首次创建）
     * 
     * @param teamId 团队ID
     * @param request HTTP请求
     * @return 初始化的密钥
     */
    @PostMapping("/initialize")
    public ApiResponse<TeamKeyDTO> initializeTeamKey(
            @PathVariable Long teamId,
            HttpServletRequest request) {
        try {
            // 验证用户身份
            Long userId = SecurityUtils.getCurrentUserId();

            logger.info("🚀 初始化团队密钥: teamId={}, userId={}", teamId, userId);

            TeamKeyDTO keyDTO = teamKeyService.initializeTeamKey(teamId, userId);

            logger.info("✅ 团队密钥初始化成功: teamId={}, keyVersion={}", teamId, keyDTO.getKeyVersion());
            return ApiResponse.success("团队密钥初始化成功", keyDTO);

        } catch (Exception e) {
            logger.error("❌ 团队密钥初始化失败: teamId={}, error={}", teamId, e.getMessage(), e);
            return ApiResponse.error("团队密钥初始化失败: " + e.getMessage());
        }
    }

    /**
     * 获取团队密钥统计信息
     * 
     * @param teamId 团队ID
     * @param request HTTP请求
     * @return 密钥统计信息
     */
    @GetMapping("/stats")
    public ApiResponse<Map<String, Object>> getKeyStats(
            @PathVariable Long teamId,
            HttpServletRequest request) {
        try {
            // 验证用户身份
            Long userId = SecurityUtils.getCurrentUserId();

            logger.info("📊 获取团队密钥统计: teamId={}, userId={}", teamId, userId);

            Map<String, Object> stats = teamKeyService.getKeyStatistics(teamId, userId);

            logger.info("✅ 成功获取密钥统计: teamId={}", teamId);
            return ApiResponse.success("获取密钥统计成功", stats);

        } catch (Exception e) {
            logger.error("❌ 获取密钥统计失败: teamId={}, error={}", teamId, e.getMessage(), e);
            return ApiResponse.error("获取密钥统计失败: " + e.getMessage());
        }
    }
}
